package org.wanda.pv.service.basic.impl;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.model.basic.Point;
import org.wanda.pv.model.basic.System;
import org.wanda.pv.service.BaseServiceImpl;
import org.wanda.pv.service.basic.SystemService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiuXuyang
 * Created by lxy on 2018/5/8.
 */

@Service
public class SystemServiceImpl extends BaseServiceImpl<System> implements SystemService {
    @Autowired
    public SystemServiceImpl(Dao dao) {
        super(dao);
    }


    /**
     * 修改排序
     *
     */
    @Transactional
    @Override
    public void updateLocation(Integer newLocation,System system){
        try{
            String sqlStr1 ="";
            //    new 3      old 5     把数据往前边提
            if (newLocation <system.getLocation()){
                sqlStr1 = "update wd_system set location = location+1 where location >=@newOrder and location<@oldOrder";
            }
            //把数据往下推
            if(newLocation >system.getLocation()){
                sqlStr1="update wd_system set location = location-1 where location >@oldOrder and location<=@newOrder";
            }
            //更新自身排序
            String sqlStr2 = "update wd_system set location = @newOrder where id = @id";
            Sql sql1 = Sqls.create(sqlStr1);
            Sql sql2 = Sqls.create(sqlStr2);
            sql1.setParam("newOrder",newLocation);
            sql1.setParam("oldOrder",system.getLocation());
            sql2.setParam("newOrder",newLocation);
            sql2.setParam("oldOrder",system.getLocation());
            sql2.setParam("id",system.getId());
            dao().execute(sql1);
            dao().execute(sql2);
        }catch (Exception e){
            throw e;
        }
    }


    @Override
    public Result add(System system) {
        try {
            if (system != null && system.getName() != null) {
                boolean distinct = this.distinct(system.getName(), system.getClass());
                if (!distinct) return Result.error("名称重复,添加失败!", "名称重复,添加失败!");
                system = this.insert(system);
                return Result.success("success", system);

            } else {
                return Result.error("数据为空,添加失败!", "数据为空,添加失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
    }


    @Override
    public Result del(Long id) {
        try {
            if(!isOk(System.class,id)){
                return Result.error("数据不存在或已删除！","数据不存在或已删除！");
            }
            Map<String, Object> hasRefer = checkHasRefer(id);
            if ((Boolean) hasRefer.get("hasRefer"))
                return Result.error((String) hasRefer.get("msg"), (String) hasRefer.get("msg"));
            System systemDesign = dao().fetch(System.class, id);
            systemDesign.setDelFlag(true);
            this.vDelete(id);
            return Result.success("success", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
    }


    @Override
    public Result updateSystem(System system) {
        try {
            System old = dao().fetch(System.class, system.getId());
            if (!old.getName().equals(system.getName())) {
                boolean distinct = this.distinct(system.getName(), system.getClass());
                if (!distinct) return Result.error("名称重复,添加失败!", "名称重复,添加失败!");
            }
            system.setDelFlag(false);
            dao().updateIgnoreNull(system);
            return Result.success("success", "操作成功!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
    }


    private Map<String, Object> checkHasRefer(Long id) {

        Map<String, Object> result = new HashMap<>();
        System system = dao().fetch(System.class, id);
        dao().fetchLinks(system, "points", Cnd.where("delFlag", "=", "0"));
        List<Point> points = system.getPoints();
        if (points != null && points.size() > 0) {
            result.put("hasRefer", true);
            result.put("msg", "有题目引用此数据,删除失败!");
            return result;
        }

        result.put("hasRefer", false);
        return result;
    }

}
